﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MyVoteMVC.Data;
using MyVoteMVC.Domain;
using MyVoteMVC.Common;
using MyVoteMVC.Common.Objects;
using MyVoteMVC.Data.Repositories;

namespace MyVoteMVC.Service
{
    public class VoteTickService : ITickService
    {
        private static object syncRoota = new Object();
        private static object syncRootb = new Object();

        private const string EmailAddress = "@gzdi.com";//接收方邮箱    
        IUnitOfWork unitOfWork;
        IRepository<VT_Tickets> ticketsRepository;
        IRepository<VT_Items> itemsRepository;
        IRepository<VT_Lotteries> lotteriesRepository;

        public VoteTickService()
        {
            unitOfWork = Factory.GetInstance<IUnitOfWork>();
            ticketsRepository = unitOfWork.GetRepository<VT_Tickets>();
            itemsRepository = unitOfWork.GetRepository<VT_Items>();
            lotteriesRepository = unitOfWork.GetRepository<VT_Lotteries>();
        }

        public bool Save(string activityID, string userID, string ticketContent, string userEmailName)
        {
            lock (syncRoota)
            {
                VT_Tickets v_Tickets = ticketsRepository.GetMany(o => o.Activity_ID == activityID && o.User_ID == userID).FirstOrDefault();
                if (v_Tickets == null)
                {
                    //为空，则增加
                    return CreateTickets(activityID, userID, ticketContent, 0, userEmailName);
                }
                else
                {
                    //VT_Tickets v_Tickets = ticketsRepository.GetMany(o => o.Activity_ID == activityID && o.Ticket_ID == ticketID).FirstOrDefault();
                    if (v_Tickets != null)
                    {
                        //编辑
                        return EditTicket(activityID, v_Tickets.Ticket_ID, ticketContent, userEmailName);
                    }
                    else
                    {   //为空，则增加
                        return CreateTickets(activityID, userID, ticketContent, 0, userEmailName);
                    }
                }
            }
        }
 
        //增加
        public bool CreateTickets(string activityID, string userID, string ticketContent, int ticketStatus, string userEmailName)
        {
            //userEmailName = userEmailName + EmailAddress;
            VT_Tickets v_Tickets= new VT_Tickets();
            unitOfWork.BeginTransaction();
            v_Tickets.Activity_ID = activityID;
            v_Tickets.Created_By = userEmailName;
            v_Tickets.Created_Date = DateTime.Now;
            v_Tickets.Ticket_Content = ticketContent;
            v_Tickets.Ticket_ID = Guid.NewGuid().ToString();
            int msx = Convert.ToInt32((from activity in ticketsRepository.QueryableEntity()
                                       where activity.Activity_ID == activityID
                                       select activity.Ticket_No).Max());
            v_Tickets.Ticket_No = msx + 1;
            v_Tickets.User_ID = userID;
            v_Tickets.Ticket_Status = ticketStatus;
            ticketsRepository.Add(v_Tickets);
            unitOfWork.CommitTransaction();
            return true;
        }
        //编辑
        public bool EditTicket(string activityID, string ticketID, string ticketContent,string userEmailName)
        {
            //userEmailName = userEmailName + EmailAddress;
            VT_Tickets v_Tickets = ticketsRepository.GetMany(o => o.Activity_ID == activityID && o.Ticket_ID == ticketID).FirstOrDefault();
            if (v_Tickets != null)
            {
                unitOfWork.BeginTransaction();
                v_Tickets.Ticket_Content = ticketContent;
                v_Tickets.Last_Update_By = userEmailName;
                v_Tickets.Last_Update_Date = DateTime.Now;
                ticketsRepository.Update(v_Tickets);
                unitOfWork.CommitTransaction();
                return true;
            }
            return false;
        }

        //删除
        public bool DeleteTicket(string activityID, string ticketID)
        {
            VT_Tickets v_Tickets = ticketsRepository.GetMany(o => o.Activity_ID == activityID && o.Ticket_ID == ticketID).FirstOrDefault();
            if (v_Tickets != null)
            {
                unitOfWork.BeginTransaction();
                ticketsRepository.Delete(v_Tickets);
                unitOfWork.CommitTransaction();
                return true;
            }
            return false;
        }

        //提交
        public bool Submit(string activityID, string userID, string ticketContent, string userEmailName)
        {
            lock (syncRootb)
            {
                unitOfWork.BeginTransaction();

                bool isSubmit = false;
                VT_Tickets v_Tickets = ticketsRepository.GetMany(o => o.Activity_ID == activityID && o.User_ID == userID).FirstOrDefault();
                if (v_Tickets != null)
                {
                    if (v_Tickets.Ticket_Status == 1)
                    {
                        isSubmit = true;
                    }
                    v_Tickets.Ticket_Content = ticketContent;
                    v_Tickets.Last_Update_By = userEmailName;
                    v_Tickets.Last_Update_Date = DateTime.Now;
                    v_Tickets.Ticket_Status = 1;
                    ticketsRepository.Update(v_Tickets);
                }
                else
                {
                    v_Tickets = new VT_Tickets();
                    v_Tickets.Activity_ID = activityID;
                    v_Tickets.Created_By = userEmailName;
                    v_Tickets.Created_Date = DateTime.Now;
                    v_Tickets.Ticket_Content = ticketContent;
                    v_Tickets.Ticket_ID = Guid.NewGuid().ToString();
                    int msx = Convert.ToInt32((from activity in ticketsRepository.QueryableEntity()
                                               where activity.Activity_ID == activityID
                                               select activity.Ticket_No).Max());
                    v_Tickets.Ticket_No = msx + 1;
                    v_Tickets.User_ID = userID;
                    v_Tickets.Ticket_Status = 1;
                    ticketsRepository.Add(v_Tickets);
                }

                if (!isSubmit)
                {
                    //更新itemm的数目
                    foreach (string ticketGroup in ticketContent.Split('&'))
                    {
                        string itemId = ticketGroup.Split('=')[1];
                        VT_Items v_items = itemsRepository.GetEntityById(itemId);
                        if (v_items != null)
                        {
                            v_items.Online_Count = v_items.Online_Count + 1;
                            itemsRepository.Update(v_items);
                        }
                    }
                }

                unitOfWork.CommitTransaction();
            }

            return true;
        }

        public bool IsCanModify(string activityID, string userID)
        {
            var pTicket = ticketsRepository.GetMany(o => o.Activity_ID == activityID && o.User_ID == userID).FirstOrDefault();
            if (pTicket != null)
            {
                if ((pTicket.Ticket_Status.HasValue?pTicket.Ticket_Status.Value:0) > 0) return false;
                return true;
            }
            else return false;
        }

        public string GetContent(string activityID, string userID)
        {
            var pTicket = ticketsRepository.GetMany(o => o.Activity_ID == activityID && o.User_ID == userID).FirstOrDefault();
            if (pTicket != null) return pTicket.Ticket_Content;
            return null;
        }

        public IList<VT_Tickets> GetTickets(string activityID,int state)
        {
            IList<VT_Tickets> v_Tickets = ticketsRepository.GetMany(o => o.Activity_ID == activityID && o.Ticket_Status == state).ToList();
            return v_Tickets;
        }
        public IList<VT_Tickets> GetTicketsNoLottery(string activityID, int state)
        {
            var v_TicketsList = from tickets in ticketsRepository.QueryableEntity()
                                where tickets.Activity_ID == activityID && tickets.Ticket_Status == state
                                select tickets;

            IList<VT_Tickets> vList = v_TicketsList.OrderBy(o => o.Ticket_No).ToList();
            IList<VT_Tickets> vTicketsList = v_TicketsList.OrderBy(o => o.Ticket_No).ToList();
            
            //检测，是否有中奖           
            foreach (VT_Tickets v_Ticket in vList)
            {
                if (IsLottery(activityID, v_Ticket.Ticket_ID) == true)
                {
                    vTicketsList.Remove(v_Ticket);
                }
            }
            return vTicketsList;
        }

        public bool IsLottery(string activityID, string ticketID)
        {
            int i = lotteriesRepository.GetMany(o => o.Activity_ID == activityID && o.Ticket_ID == ticketID && o.Lottery_TypeValue == 1).Count();
            if (i > 0)
                return true;
            else return false;
        }

        public void ReComputeTicket()
        {
            unitOfWork.BeginTransaction();
            var pItemList = itemsRepository.GetAll();
            foreach (var pItem in pItemList)
            {                
                pItem.Online_Count = 0;
            }

            var pTicketList = ticketsRepository.GetMany(o => o.Ticket_Status.Value == 1);
            foreach (var pTicket in pTicketList)
            {
                foreach (string ticketGroup in pTicket.Ticket_Content.Split('&'))
                {
                    string itemId = ticketGroup.Split('=')[1];
                    VT_Items v_items = itemsRepository.GetEntityById(itemId);
                    if (v_items != null)
                    {
                        v_items.Online_Count = v_items.Online_Count + 1;
                        itemsRepository.Update(v_items);
                    }
                }
            }
            unitOfWork.CommitTransaction();
        }

        #region IDisposable Members

        private bool m_disposed;
        protected virtual void Dispose(bool disposing)
        {
            if (!m_disposed)
            {
                if (disposing)
                {
                    unitOfWork.Dispose();   
                }

                // Release unmanaged resources

                m_disposed = true;
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        ~VoteTickService()
        {
            Dispose(false);
        }
        #endregion
    }
}